package fr.resasante.utils;

import java.io.InputStream;
import java.util.Iterator;

import javax.naming.NamingException;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import fr.resasante.exception.ApplicationException;

/**
 * Class for getting jobs in XML
 * 
 * @author GEFFROY-DE-VILLEBLAN
 * 
 */
public final class JobsUtils {
	/**
	 * Properties class instance
	 */
	private static volatile JobsUtils instance = null;

	/**
	 * Root element
	 */
	private Element root;

	/**
	 * Constructor
	 */
	private JobsUtils() {
		super();
		loadXmlFile();
	}

	/**
	 * Method returning a Singleton class instance
	 * 
	 * @return Singleton instance
	 * @throws NamingException
	 */
	public final static JobsUtils getInstance() {
		if (JobsUtils.instance == null) {
			synchronized (JobsUtils.class) {
				if (JobsUtils.instance == null) {
					JobsUtils.instance = new JobsUtils();
				}
			}
		}
		return JobsUtils.instance;
	}

	/**
	 * Load the XML file
	 */
	private void loadXmlFile() {
		try {
			InputStream xmlStream = this.getClass().getClassLoader()
					.getResourceAsStream("jobs.xml");
			SAXReader reader = new SAXReader();
			Document doc = reader.read(xmlStream);
			root = doc.getRootElement();
		} catch (Exception e) {
			throw new ApplicationException("Unable to find the XML file jobs.xml", e);
		}
	}

	/**
	 * Check if the job name exists
	 * 
	 * @param jobName
	 *            The job name
	 * @return true if the job exists, false if it doesn't exist
	 */
	public Boolean isJobExists(String jobName) {
		@SuppressWarnings("rawtypes")
		Iterator iterator = root.elementIterator("job");
		while (iterator.hasNext()) {
			Element job = (Element) iterator.next();
			String jobLabel = job.elementText("label");
			if (jobName.equals(jobLabel)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * Check if the speciality exists. The speciality must match the passed job
	 * name
	 * 
	 * @param jobName
	 *            The job name
	 * @param specialityName
	 *            The speciality name
	 * @return true if the speciality exists, false if it doesn't exist
	 */
	public Boolean isSpecialityExists(String jobName, String specialityName) {
		@SuppressWarnings("rawtypes")
		Iterator iteratorJob = root.elementIterator("job");
		while (iteratorJob.hasNext()) {
			Element job = (Element) iteratorJob.next();
			String jobLabel = job.elementText("label");
			if (jobName.equals(jobLabel)) {
				Element specialities = job.element("specialities");
				@SuppressWarnings("rawtypes")
				Iterator iteratorSpeciality = specialities.elementIterator("speciality");
				while (iteratorSpeciality.hasNext()) {
					Element speciality = (Element) iteratorSpeciality.next();
					if (specialityName.equals(speciality.getText())) {
						return true;
					}
				}
			}
		}
		return false;
	}
}